package com.meiyu.live.ui.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.net.FileReqPackage;
import com.meiyu.live.net.UploadFile;
import com.meiyu.live.net.callback.UploadCallBack;
import com.meiyu.live.net.param.CreateHookupParams;
import com.meiyu.live.net.param.UploadFileParams;
import com.meiyu.live.net.response.BaseResponse;
import com.meiyu.live.net.response.UploadResponse;
import com.meiyu.live.popj.PlanDate;
import com.meiyu.live.util.BitmapUtil;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.NetLoadingDailog;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import vn.tungdx.mediapicker.MediaItem;
import vn.tungdx.mediapicker.MediaOptions;
import vn.tungdx.mediapicker.activities.MediaPickerActivity;

/**
 * 主播资料
 * Created by zbl on 2016/9/22.
 */
public class Apply2Activity extends BaseActivity implements View.OnClickListener {

    public static final String DATA_START_TIME = "data_start_time";
    public static final String DATA_END_TIME = "data_end_time";
    public static final String DATA_CHANNEL_STATUS = "data_channel_status";
    public static final String DATA_ASSORT_ID = "data_assort_id";
    public static final String DATA_TOTAL_SHARES = "data_TOTAL_SHARES";

    private static final int REQUEST_MEDIA = 100;
    ExecutorService pool = Executors.newFixedThreadPool(6);
    private NetLoadingDailog dialog_loading;

    private View btn_back, btn_skip;
    private TextView btn_apply;
    private EditText et_description;

    private RecyclerView imgs, videos;

    GalleryAdapter imgsAdapter;
    GalleryAdapter videoAdapter;
    private List<MediaItem> imgDatas;
    private List<MediaItem> videoDatas;

    private int uploadSucNum = 0;

    private String startTimeText, endTimeText;
    private int channel_status, total_shares, assort_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply2);
        Intent intent = getIntent();
        startTimeText = intent.getStringExtra(DATA_START_TIME);
        endTimeText = intent.getStringExtra(DATA_END_TIME);
        channel_status = intent.getIntExtra(DATA_CHANNEL_STATUS, 0);
        total_shares = intent.getIntExtra(DATA_TOTAL_SHARES, 0);
        assort_id = intent.getIntExtra(DATA_ASSORT_ID, 0);
        init();
    }

    private void init() {
        dialog_loading = new NetLoadingDailog(this);
        imgs = (RecyclerView) findViewById(R.id.imgs);
        imgs.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        videos = (RecyclerView) findViewById(R.id.videos);
        videos.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        et_description = (EditText) findViewById(R.id.et_description);

        btn_apply = (TextView) findViewById(R.id.btn_apply);
        btn_apply.setOnClickListener(this);

        imgDatas = new ArrayList<MediaItem>();
        videoDatas = new ArrayList<MediaItem>();
        imgsAdapter = new GalleryAdapter(Apply2Activity.this, imgDatas, GalleryAdapter.TYPE_IMG);
        videoAdapter = new GalleryAdapter(this, videoDatas, GalleryAdapter.TYPE_VIDEO);
        imgs.setAdapter(imgsAdapter);
        videos.setAdapter(videoAdapter);

        btn_back = findViewById(R.id.btn_back);
        btn_skip = findViewById(R.id.btn_skip);
        btn_back.setOnClickListener(this);
        btn_skip.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (TextUtils.isEmpty(et_description.getText().toString())) {
            ToastUtil.show("请填写描述");
            return;
        }
        if (view == btn_back) {
            finish();
        } else if (view == btn_skip) {
//            dialog_loading.loading();
//            postData("");
        } else if (view == btn_apply) {
            dialog_loading.loading();
            if (videoDatas.size() == 0 && imgDatas.size() == 0) {
                postData(et_description.getText().toString());
                return;
            }
            String body = new FileReqPackage(new UploadFileParams("video")).packetParam();
            for (MediaItem mediaItem : videoDatas) {
                if (mediaItem.getStatus() == MediaItem.UPLOAD) {
                    continue;
                }
                pool.execute(new UploadFile(MediaItem.VIDEO,
                        videoDatas.indexOf(mediaItem),
                        Constant.URL + Constant.UrlParams.UPLOAD,
                        mediaItem.getPathOrigin(Apply2Activity.this),
                        body,
                        callBack));
            }

            body = new FileReqPackage(new UploadFileParams("cover")).packetParam();
            for (MediaItem mediaItem : imgDatas) {
                if (mediaItem.getStatus() == MediaItem.UPLOAD) {
                    continue;
                }
                pool.execute(new UploadFile(MediaItem.PHOTO,
                        imgDatas.indexOf(mediaItem),
                        Constant.URL + Constant.UrlParams.UPLOAD,
                        mediaItem.getPathOrigin(Apply2Activity.this),
                        body,
                        callBack));
            }

        }
    }

    UploadCallBack callBack = new UploadCallBack() {
        @Override
        public void response(UploadResponse response) {
            if (response.getCode() == 200) {
                if (response.getType() == MediaItem.VIDEO) {
                    String body = new FileReqPackage(new UploadFileParams("video_cover", response.getHash().getId())).packetParam();
                    pool.execute(new UploadFile(response.getPosition(),
                            Constant.URL + Constant.UrlParams.UPLOAD,
                            BitmapUtil.getFirstPicFromVideo(response.getFilepath()),
                            "video_pic.jpg",
                            body,
                            callBack));
                } else {
                    if (response.getType() == MediaItem.PHOTO) {
                        imgDatas.get(response.getPosition()).setStatus(MediaItem.UPLOAD);
                    } else {
                        videoDatas.get(response.getPosition()).setStatus(MediaItem.UPLOAD);
                    }
                    uploadSucNum++;
                    if (isAllFileUpload(uploadSucNum)) {
                        uploadSuc();
                    }
                }

            } else {
                uploadError();
            }
        }
    };

    private boolean isAllFileUpload(int num) {
        return num >= videoDatas.size() + imgDatas.size();
    }

    private void uploadError() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.show("提交失败请重试");
                dialog_loading.dismissDialog();
            }
        });
    }

    private void uploadSuc() {
        uploadSucNum = 0;
        videoDatas.clear();
        imgDatas.clear();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                videoAdapter.notifyDataSetChanged();
//                imgsAdapter.notifyDataSetChanged();
//                dialog_loading.dismissDialog();
                postData(et_description.getText().toString());
            }
        });
    }

    private void postData(String description) {
        if (TextUtils.isEmpty(et_description.getText().toString())) {
            ToastUtil.show("请填写描述");
        } else if (imgDatas.size() < 0) {
            ToastUtil.show("请上传图片");
        } else {
            //发起约播
            List<PlanDate> dates = new ArrayList<>();
            dates.add(new PlanDate(startTimeText, endTimeText));
            request(new CreateHookupParams(total_shares, channel_status, description, assort_id, "", 1, dates), BaseResponse.class, new Response.Listener<BaseResponse>() {
                @Override
                public void onResponse(BaseResponse onlyStatusResponse) {
                    dialog_loading.dismissDialog();
                    if (onlyStatusResponse != null) {
                        if (onlyStatusResponse.getStatusCode() == Constant.StatusCode_Success) {
                            ToastUtil.show("申请成功");
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            ToastUtil.show("申请失败," + onlyStatusResponse.getMsg());
                        }
                    } else {
                        ToastUtil.show("申请失败");
                    }

                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_MEDIA) {
            if (resultCode == RESULT_OK) {
                List<MediaItem> mMediaSelectedList = MediaPickerActivity
                        .getMediaItemSelected(data);
                if (mMediaSelectedList != null) {
                    for (MediaItem mediaItem : mMediaSelectedList) {
                        if (mediaItem.getType() == MediaItem.PHOTO) {
                            imgDatas.add(mediaItem);
                            imgsAdapter.notifyDataSetChanged();
                        } else {
                            videoDatas.add(mediaItem);
                            videoAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        }
    }

    public class GalleryAdapter extends
            RecyclerView.Adapter<GalleryAdapter.ViewHolder> {

        /**
         * ItemClick的回调接口
         *
         * @author zhy
         */

        public static final int TYPE_IMG = 0;
        public static final int TYPE_VIDEO = 1;
        private LayoutInflater mInflater;
        private List<MediaItem> mDatas;
        private int type;

        public GalleryAdapter(Context context, List<MediaItem> datas, int type) {
            super();
            mInflater = LayoutInflater.from(context);
            this.mDatas = datas;
            this.type = type;
        }


        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((int) v.getTag() == mDatas.size()) {
                    MediaOptions.Builder builder = new MediaOptions.Builder();
                    MediaOptions options;
                    if (type == TYPE_VIDEO) {
                        options = builder.selectVideo().setMaxVideoDuration(20 * 1000)
                                .build();
                    } else {
                        options = MediaOptions.createDefault();
                    }
                    if (options != null) {
                        MediaPickerActivity.open(Apply2Activity.this, REQUEST_MEDIA, options);
                    }
                }
            }
        };

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(View arg0) {
                super(arg0);
            }

            ImageView mImg;
            ImageView del;
        }

        @Override
        public int getItemCount() {
            return mDatas.size() + 1;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = mInflater.inflate(R.layout.item_mediapicke,
                    viewGroup, false);
            ViewHolder viewHolder = new ViewHolder(view);

            viewHolder.mImg = (ImageView) view
                    .findViewById(R.id.image);
            viewHolder.del = (ImageView) view
                    .findViewById(R.id.del);
            viewHolder.del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (type == TYPE_IMG) {
                        imgDatas.remove((int) v.getTag());
                        imgsAdapter.notifyDataSetChanged();
                    } else {
                        videoDatas.remove((int) v.getTag());
                        videoAdapter.notifyDataSetChanged();
                    }
                }
            });
            viewHolder.itemView.setOnClickListener(onClickListener);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
            if (i != mDatas.size()) {
                MediaItem mediaItem = mDatas.get(i);
                viewHolder.del.setVisibility(View.VISIBLE);
                viewHolder.del.setTag(i);
                if (mediaItem.getPathCropped(Apply2Activity.this) == null) {
                    ImageLoader.getInstance().displayImage(mediaItem.getUriOrigin().toString(), viewHolder.mImg);
                } else {
                    ImageLoader.getInstance().displayImage(mediaItem.getUriCropped().toString(), viewHolder.mImg);
                }
            } else {
                if (type == TYPE_VIDEO) {
                    viewHolder.mImg.setImageResource(R.drawable.add_video);
                } else {
                    viewHolder.mImg.setImageResource(R.drawable.add_img);
                }
                viewHolder.del.setVisibility(View.GONE);
            }
            viewHolder.itemView.setTag(i);

        }

    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onError() {
        super.onError();
        dialog_loading.dismissDialog();
    }
}
